<?php
namespace dwc_app;

class FusionArchiveUploader
{
    public $dwca;
    public $fusion_tables_api;
    
    function __construct($dwca, $username, $password)
    {
        $this->dwca = $dwca;
        
        $this->fusion_tables_api = new GoogleFusionAPI($username, $password, @$_SESSION['GOOGLE_AUTH_TOKEN'], 'tdwgcodeblitz-dwc_fusion_tables-0.1');
    }
    
    public function send_core_to_fusion_tables()
    {
        $this->send_core_or_extension_to_fusion_tables($this->dwca->core);
        $this->send_extensions_to_fusion_tables();
    }
    
    public function send_extensions_to_fusion_tables()
    {
        foreach($this->dwca->extensions as $extension)
        {
            $this->send_core_or_extension_to_fusion_tables($extension);
        }
    }
    
    public function send_core_or_extension_to_fusion_tables($core_or_extension)
    {
        $table_name = $core_or_extension->row_type;
        if(preg_match("/\/([^\/]+)$/", $table_name, $arr))
        {
            $table_name = $arr[1];
        }
        
        $fusion_table_fields = array();
        foreach($core_or_extension->fields as $field)
        {
            if(preg_match("/\/([^\/]+)$/", $field['term'], $arr))
            {
                $row_type = 'STRING';
                if(preg_match("/^(locality|continent|country|decimallatitude|decimallongitude)$/i", $arr[1])) $row_type = 'LOCATION';
                elseif(preg_match("/^(modified|.*date)$/i", $arr[1])) $row_type = 'DATETIME';
                $fusion_table_fields[$arr[1]] = $row_type;
            }
        }
        $table_id = $this->fusion_tables_api->create_table($table_name, $fusion_table_fields);
        $this->send_core_or_extension_data_to_fusion_tables($table_id, $fusion_table_fields, $core_or_extension);
        echo "<a href=http://tables.googlelabs.com/DataSource?dsrcid=$table_id>See the table</a><br><br><br>";
    }
    
    public function send_core_or_extension_data_to_fusion_tables($table_id, $fusion_table_fields, $core_or_extension)
    {
        $file_contents = get_remote_file($core_or_extension->file_uri);
        $lines = explode($core_or_extension->lines_terminated_by, $file_contents);
        
        $row_data = array();
        $line_num = 0;
        foreach($lines as $line)
        {
            $line_num++;
            if($core_or_extension->ignore_header_lines && $line_num == 1) continue;
            if(!trim($line)) continue;
            if($core_or_extension->fields_enclosed_by)
            {
                $line = str_replace($core_or_extension->fields_terminated_by.$core_or_extension->fields_terminated_by, $core_or_extension->fields_terminated_by.$core_or_extension->fields_enclosed_by.$core_or_extension->fields_enclosed_by.$core_or_extension->fields_terminated_by, $line);
                $line = str_replace($core_or_extension->fields_terminated_by.$core_or_extension->fields_terminated_by, $core_or_extension->fields_terminated_by.$core_or_extension->fields_enclosed_by.$core_or_extension->fields_enclosed_by.$core_or_extension->fields_terminated_by, $line);
                if(substr($line, -1) == $core_or_extension->fields_terminated_by)
                {
                    $line .= $core_or_extension->fields_enclosed_by.$core_or_extension->fields_enclosed_by;
                }
            }
            $line = preg_replace("/^".preg_quote($core_or_extension->fields_enclosed_by, "/")."/", "", $line);
            $line = preg_replace("/".preg_quote($core_or_extension->fields_enclosed_by, "/")."$/", "", $line);
            $fields = explode($core_or_extension->fields_enclosed_by.$core_or_extension->fields_terminated_by.$core_or_extension->fields_enclosed_by, $line);
            if($fields)
            {
                foreach($fields as $key => $value) $fields[$key] = str_replace("'", "\'", $value);
                $row_data[] = "INSERT INTO $table_id ('". implode("', '", array_keys($fusion_table_fields))."') VALUES ('". implode("','", $fields) ."');";
            }
            if(count($row_data) >= 500)
            {
                echo "Inserting batch of 500<br>";
                ob_end_flush();
                ob_flush();
                flush();
                ob_start();
                $this->fusion_tables_api->query(implode(" ", $row_data));
                $row_data = array();
                //break;
            }
        }
        if($row_data)
        {
            echo "Inserting remaining batch of ".count($row_data)."<br>";
            ob_end_flush();
            ob_flush();
            flush();
            ob_start();
            $this->fusion_tables_api->query(implode(" ", $row_data));
            unset($row_data);
        }
    }
}

?>